import 'dart:ui';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: PathAnimationDemo(),
    );
  }
}

class PathAnimationDemo extends StatefulWidget {
  @override
  _PathAnimationDemoState createState() => _PathAnimationDemoState();
}

class _PathAnimationDemoState extends State<PathAnimationDemo>
    with SingleTickerProviderStateMixin {
  late AnimationController animationController;
  late Animation<double> _animation;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //0 ~ 1
    animationController = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('绘制专题')),
      body: Center(
        child: Container(
          width: 500,
          height: 500,
          color: Colors.blue.shade100,
          child: AnimatedBuilder(
            animation: animationController,
            builder: (BuildContext context, Widget? child) {
              return CustomPaint(
                size: Size(500, 500),
                //画布
                //绘制工作
                painter: PathPainter(animationController),
              );
            },
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          animationController.forward(from: 0);
        },
      ),
    );
  }
}

class PathPainter extends CustomPainter {
  final Paint _paint = Paint()
    //颜色
    ..color = Colors.red
    //填充方式
    ..style = PaintingStyle.stroke
    //拐角的样式
    ..strokeCap = StrokeCap.round
    //宽度
    ..strokeWidth = 10;

  AnimationController animationController;
  PathPainter(this.animationController);
  @override
  void paint(Canvas canvas, Size size) {
    Path path = Path();
    path.moveTo(40, 40);
    path.lineTo(300, 40);
    path.lineTo(300, 400);

    //测量
    final PathMetrics pathMetrics = path.computeMetrics();
    //
    final PathMetric first = pathMetrics.first;

    //提取子路径
    final childPath = first.extractPath(
      0,
      first.length * animationController.value,
    );

    //绘制子路径
    canvas.drawPath(childPath, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
